package com.szcinda.service.dto.baoGuanType;

import com.szcinda.repository.BaoGuanType;
import com.szcinda.repository.BaoGuanTypeRepository;
import com.szcinda.service.SnowFlakeFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

@Service
@Transactional
public class BGTypeServiceImpl implements BGTypeService {
    private final BaoGuanTypeRepository baoGuanTypeRepository;
    private final SnowFlakeFactory snowFlakeFactory;

    public BGTypeServiceImpl(BaoGuanTypeRepository baoGuanTypeRepository) {
        this.baoGuanTypeRepository = baoGuanTypeRepository;
        this.snowFlakeFactory = SnowFlakeFactory.getInstance();
    }

    @Override
    public void create(CreateBGTypeDto createBGTypeDto) {
        BaoGuanType baoGuanType = baoGuanTypeRepository.findByName(createBGTypeDto.getName());
        Assert.isTrue(baoGuanType == null, "存在相同报关方式的记录");
        baoGuanType = new BaoGuanType();
        BeanUtils.copyProperties(createBGTypeDto, baoGuanType);
        baoGuanType.setId(snowFlakeFactory.nextId("BT"));
        baoGuanTypeRepository.save(baoGuanType);
    }

    @Override
    public void delete(String id, String userId) {
        baoGuanTypeRepository.delete(id);
    }

    @Override
    public List<BaoGuanType> findAll() {
        return baoGuanTypeRepository.findAll();
    }

    @Override
    public void batchCreate(List<BGTypeImportDto> importDatas, String opId) {
        List<BaoGuanType> baoGuanTypes = baoGuanTypeRepository.findAll();
        for (BGTypeImportDto importDto : importDatas) {
            boolean b = baoGuanTypes.stream().noneMatch(baoGuanType -> baoGuanType.getName().equals(importDto.getName()));
            if (b) {
                BaoGuanType baoGuanType = new BaoGuanType();
                BeanUtils.copyProperties(importDto, baoGuanType);
                baoGuanType.setId(snowFlakeFactory.nextId("BT"));
                baoGuanTypeRepository.save(baoGuanType);
            }
        }
    }
}
